package com.gaohe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaohe.common.Result;
import com.gaohe.common.ResultMessage;
import com.gaohe.mapper.AdminMapper;
import com.gaohe.pojo.Admin;
import com.gaohe.service.AdminService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 登录
     * @param request 请求对象
     * @param admin 用户信息
     * @return
     */
    @Override
    public Result login(HttpServletRequest request, Admin admin) {
        //1.密码加密
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        //2.根据用户名 和密码 查询
        LambdaQueryWrapper<Admin> qw = new LambdaQueryWrapper<>();
        qw.eq(Admin::getUsername, admin.getUsername())
                .eq(Admin::getPassword, admin.getPassword());
        Admin selectAdmin = adminMapper.selectOne(qw);
        //3.判断是否为空  空 返回错误结果
        if (Objects.isNull(selectAdmin)) {
            return Result.error(ResultMessage.USERNAME_OR_PASSWORD_ERROR);
        }
        //4.判断 status == 0 禁用 返回错误结果
        if (selectAdmin.getStatus() == 0) {
            return Result.error(ResultMessage.ACCOUNT_DISABLED);
        }
        //5.存 session
//        request.getSession().setAttribute("loginAdmin",selectAdmin);
        //存 redis  设置过期时间  30min 1h
        ValueOperations ops = redisTemplate.opsForValue();
        //设置 key 唯一  传递
        ops.set(
                "admin_"+selectAdmin.getAdminId(),
                selectAdmin,
                30,
                TimeUnit.MINUTES
        );

        //6.响应成功结果
        return Result.success(selectAdmin,ResultMessage.LOGIN_SUCCESS);
    }

    /**
     * 推出登录
     * @param request
     * @return
     */
    @Override
    public Result logout(HttpServletRequest request) {
//        request.getSession().removeAttribute("loginAdmin");

        ValueOperations ops = redisTemplate.opsForValue();
        //获取请求头中的 id
        String adminId = request.getHeader("admin");
        String redisKey = "admin_" + adminId;
        Object redisAdmin = ops.get(redisKey);
        //判断
        if (Objects.nonNull(redisAdmin)){
            redisTemplate.delete(redisKey);
        }
        return Result.success(ResultMessage.LOGOUT_SUCCESS);
    }
}
